/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.treepoke.util.jms;

import com.treepoke.util.exception.UtilException;
import com.treepoke.util.location.ServiceLocator;
import java.io.Serializable;
import javax.jms.*;
import javax.naming.Context;
import javax.naming.NamingException;

public class JMSUtil {
    
    public static void enviarMensajeCola(String queueName,
            String connectionFactoryName, Serializable mensaje) throws UtilException {
        enviarMensajeCola(queueName, connectionFactoryName, mensaje, null);
    }
    
    public static void enviarMensajeCola(String queueName, 
        String connectionFactoryName, Serializable mensaje, Integer tipoMensaje) throws UtilException {
        try {
            Context ctx = ServiceLocator.getInstance().getContext();
            QueueConnectionFactory qconFactory;
            QueueConnection connection;
            QueueSession session;
            QueueSender sender;
            Queue queue;
            ObjectMessage msg;
            qconFactory = (QueueConnectionFactory) ctx.lookup(connectionFactoryName);
            connection = qconFactory.createQueueConnection();
            session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
            queue = (Queue) ctx.lookup(queueName);
            msg = session.createObjectMessage();
            sender = session.createSender(queue);
            if (tipoMensaje != null) {
                msg.setIntProperty("tipoMensaje", tipoMensaje);
            }            
            msg.setObject(mensaje);
            connection.start();
            sender.send(msg);
            session.close();
            connection.close();
        } catch (JMSException ex) {
            throw new UtilException("Error en mensajería: " + ex.getMessage(), ex, 0);
        } catch (NamingException ex) {
            throw new UtilException("Error buscando recurso: " + ex.getMessage(), ex, 0);
        }
    }
    
}
